package com.example.governmentcrawler.service.impl;

import cn.hutool.extra.mail.Mail;
import cn.hutool.extra.mail.MailAccount;
import com.example.governmentcrawler.service.EmailService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @projectName: GovernmentCrawler
 * @package: com.example.governmentcrawler.service.impl
 * @className: EmailServiceImpl
 * @author: xxXPCSC
 * @description: TODO
 * @date: 2024/2/26 19:41
 * @version: 1.0
 **/
@Service
public class EmailServiceImpl implements EmailService {
    @Value("${spring.mail.email}")
    private String email;
    @Value("${spring.mail.host}")
    private String host;
    @Value("${spring.mail.port}")
    private String port;
    @Value("${spring.mail.username}")
    private String username;
    @Value("${spring.mail.password}")
    private String password;

    @Override
    public void send(String mail,List<String> fail) {
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String day = currentDate.format(formatter);

        // 读取邮箱配置
        if (email == null || host == null || port == null || username == null || password == null) {
            throw new RuntimeException("邮箱配置异常");
        }
        // 设置
        MailAccount account = new MailAccount();
        account.setHost(host);
        account.setPort(Integer.parseInt(port));
        // 设置发送人邮箱
        account.setFrom(username + "<" + email + ">");
        // 设置发送人名称
        account.setUser(username);
        // 设置发送授权码
        account.setPass(password);

        account.setAuth(true);
        // ssl方式发送
        account.setSslEnable(true);
        // 使用安全连接
        account.setStarttlsEnable(true);
        System.out.println(account);

        List<String> strings = Collections.singletonList(mail);

        StringBuilder mymsg = new StringBuilder();
        mymsg.append("<h1>截至时间为"+day+"</h1>");
        if(fail.isEmpty())
            mymsg.append("<p style='font-family:STHeiti; font-size:23px;'>三封邮件全部发送成功</p>");
        else
            mymsg.append("<p style='font-family:STHeiti; font-size:23px;'>"+fail.toString()+" 发送失败<p>");

//        for (String key:
//             keySet) {
//            mymsg.append("<p><a href="+ UrlConst.GovDetailUrl+key+">"+msg.get(key)+"</a></p>"+"\n");
//
//        }
        String s = mymsg.toString();
        // 发送邮件
        try {
            int size = strings.size();
            Mail.create(account)
                    .setTos(strings.toArray(new String[size]))
                    .setTitle("伊索斯公司相关项目投标订阅信息")
                    .setContent(s)
                    .setHtml(true)
                    //关闭session
                    .setUseGlobalSession(false)
                    .send();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public Boolean sendDay(String mail, Map<String, Map> msg) {
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String day = currentDate.format(formatter);

        // 读取邮箱配置
        if (email == null || host == null || port == null || username == null || password == null) {
            throw new RuntimeException("邮箱配置异常");
        }
        // 设置
        MailAccount account = new MailAccount();
        account.setHost(host);
        account.setPort(Integer.parseInt(port));
        // 设置发送人邮箱
//        account.setUser("Get");
        account.setFrom(username+"<"+email+">");
        // 设置发送人名称
        account.setUser(username);
        // 设置发送授权码
        account.setPass(password);

        account.setAuth(true);
        // ssl方式发送
        account.setSslEnable(true);
        // 使用安全连接
        account.setStarttlsEnable(true);
        List<String> strings = Collections.singletonList(mail);

        StringBuilder mymsg = new StringBuilder();
        Set<String> keySet = msg.keySet();
        mymsg.append("<h1 style='text-align: center;'>伊索斯公司相关项目投标订阅信息</h1>");
        mymsg.append("<div style='text-align: center;'><h2 style='font-size: 18px;'>截至时间为"+day+"</h2></div><p></p>");
        int i=1;

        //最外层的是政府网站信息
        for(String outkey:keySet){
            mymsg.append("<p style='font-size: 23px;font-family:STHeiti;'>"+outkey+"</p>"+"\n");
            //中间层的的map 表示分为两个标题

            Map<String, Map> midMap = msg.get(outkey);
            if(midMap.size()==0){
                mymsg.append("<p style='color:red;font-size: 18px;'>暂无符合数据<p>");
                continue;
            }
            for(String innerKey:midMap.keySet()){
                i=1;
                mymsg.append("<p style='font-size: 20px;font-family:STHeiti;'>"+innerKey+"</p>");
                //外层的key是title
                Map<String,String> innerMap = midMap.get(innerKey);
                if(innerMap.size()==0) {
                    mymsg.append("<p style='color:red;font-size: 18px;'>暂无符合数据</p>");
                    continue;
                }
                for(String title : innerMap.keySet()){
                    mymsg.append("<p style='font-size: 18px;'><a href="+innerMap.get(title)+">"+i+"、"+title+"</a></p>"+"\n");
                    i++;
                }
            }
        }


        String s =mymsg.toString();
        // 发送邮件
        try {
            int size = strings.size();
            Mail.create(account)
                    .setTos(strings.toArray(new String[size]))
                    .setTitle("伊索斯公司相关项目投标订阅信息")
                    .setContent(s)
                    .setHtml(true)
                    //关闭session
                    .setUseGlobalSession(false)
                    .send();
        } catch (Exception e) {
            System.out.println((e.getMessage()));
            return false;
        }
        return true;
    }


}
